package cn.edu.sdju.wanglo1911.team10.service;

import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.edu.sdju.wanglo1911.team10.dao.OrderItemDao;
import cn.edu.sdju.wanglo1911.team10.po.Book;
import cn.edu.sdju.wanglo1911.team10.po.OrderItem;
import cn.edu.sdju.wanglo1911.team10.po.OrderSummary;
import cn.edu.sdju.wanglo1911.team10.po.QueryOption;
import cn.edu.sdju.wanglo1911.team10.po.ShoppingCartItem;
import cn.edu.sdju.wanglo1911.team10.utillity.Helper;


@Service
public class OrderServiceImpl implements OrderService {

	@Autowired
	private OrderItemDao orderItemDao;
	@Autowired
	private BookService bookService;
	@Autowired
	private ShoppingCartService shoppingCartService;
	
	public List<OrderItem> getAllItemByUserId(String userId) {
		// TODO Auto-generated method stub
		return orderItemDao.getAllItemByUserId(userId);
	}

	@Transactional
	public void createOrder(List<ShoppingCartItem> shoppingCartItems) {
		List<String> ids = new ArrayList<String>();
		String orderNo = Helper.genOrderNo();
		for (ShoppingCartItem shoppingCartItem : shoppingCartItems) {
			OrderItem orderItem = new OrderItem();
			Book book = bookService.getBookById(shoppingCartItem.getBookId());
			orderItem.setOrderNo(orderNo);
			orderItem.setUserId(shoppingCartItem.getUserId());
			orderItem.setBookId(shoppingCartItem.getBookId());  
			orderItem.setBookTitle(book.getTitle());
			orderItem.setPrice(book.getPrice());
			orderItem.setAmount(shoppingCartItem.getAmount());
			ids.add(book.getId());
			orderItemDao.insertItem(orderItem);
		}
		shoppingCartService.deleteAllByUserId(shoppingCartItems.get(0).getUserId());
	}

	public List<OrderSummary> advanceQuery(QueryOption option) {
		// TODO Auto-generated method stub
		return orderItemDao.advanceQuery(option);
	}

	public Integer getTotalQueryNumber(QueryOption option) {
		// TODO Auto-generated method stub
		return orderItemDao.getTotalQueryNumber(option);
	}

	public List<OrderItem> getAllItemByOrderNo(String orderNo) {
		// TODO Auto-generated method stub
		return orderItemDao.getAllItemByOrderNo(orderNo);
	}

	public void deleteAllByOrderNo(List<String> orderNos) {
		// TODO Auto-generated method stub
		orderItemDao.deleteAllByOrderNo(orderNos);
	}

	public void updateOrder(OrderSummary order) {
		// TODO Auto-generated method stub
		orderItemDao.updateOrder(order);
	}

}
